package com.example.duihua.service.impl;

import com.example.duihua.entity.Message;
import com.example.duihua.mapper.MessageMapper;
import com.example.duihua.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public Message save(Message message) {
        // 保存消息到数据库
        messageMapper.insert(message);
        return message;
    }

    @Override
    public List<Message> getPrivateMessages(Long userId, Long friendId, int page, int size) {
        // 获取私聊消息历史
        int offset = (page - 1) * size;
        return messageMapper.findPrivateMessages(userId, friendId, offset, size);
    }

    @Override
    public List<Message> getGroupMessages(Long groupId, int page, int size) {
        // 获取群聊消息历史
        int offset = (page - 1) * size;
        return messageMapper.findGroupMessages(groupId, offset, size);
    }

    @Override
    public boolean markAsRead(List<Long> messageIds) {
        // 标记消息为已读
        if (messageIds == null || messageIds.isEmpty()) {
            return false;
        }
        return messageMapper.updateStatus(messageIds, "READ") > 0;
    }

    @Override
    public boolean recallMessage(Long messageId, Long userId) {
        // 撤回消息（只能撤回自己发送的消息）
        Message message = messageMapper.findById(messageId);
        if (message != null && message.getSenderId().equals(userId)) {
            message.setStatus("RECALLED");
            return messageMapper.update(message) > 0;
        }
        return false;
    }
}